/* Movelist.java
 * A list of moves made so far in the game,
 * along with memory of which is the current move.
 */
package tictactoe;
import java.util.ArrayList;


public class MoveList {
	//Constructor, creates a new empty list of moves
	public MoveList() {
		moves = new ArrayList<Square>();
		index = -1;
	}
	//This constructor is used to copy the movelist in newInstance
	public MoveList(ArrayList<Square> moves, int index) {
		this.index = index;
		this.moves = new ArrayList<Square>();
		for(int move_num = 0; move_num < moves.size(); move_num++) {
			this.moves.add(moves.get(move_num));
		}
	}
	// Returns a copy of the current movelist
	public MoveList newInstance() {
		return new MoveList(moves,index);
	}
	
	public void reset() {
		// empties an existing list of moves
		moves.clear();
		index = -1;
	}
	
	public void addMove(Square move) {
		// adds new move to list and makes that the current move
		// if there were moves stored beyond the current move, remove them
		// because they were undone before the current move
                // remove moves until the current move is the last.
		while(moves.size() - 1 != index) {
			moves.remove(moves.size() - 1);
		}
                moves.add(move);
		index++;
	}
	
	public Square undo() {
		// makes the previous move the current move and returns the (old)
		// current move
		// if the current move is -1, then it refers to an empty board and
		// there are no moves to undo
		if(index >= 0) {
			index--;
			return moves.get(index + 1);
		}
		return null;
	}
	
	public Square redo() {
		// makes the next move the current move and return it   
		// if the current move is the last move, do nothing
		if(index == moves.size() - 1) {
			return null;
		}
		index++;
		return moves.get(index);
	}
	
	private ArrayList<Square> moves; //all moves that have been made
	private int index; // index of last move made in the current game state
}
